﻿"use strict";

var firebaseApp = {};
firebaseApp.shipsArray = [];

firebaseApp.create = function () {
    var name = document.getElementById('name').value;
    var affiliation = document.getElementById('affiliation').value;
    var isImpoundedRadios = document.getElementsByName('isImpounded');
    var isImpounded = isImpoundedRadios[0].checked ? true : false;
    
    var data = {
        name: name,
        affiliation: affiliation,
        isImpounded: isImpounded
    };

    var request = new XMLHttpRequest();

    request.open('POST', 'https://sweltering-torch-7921.firebaseio.com/.json', false);
    request.onload = function () {
        //Parse the response into a JavaScript object
        var obj = JSON.parse(this.response);

        //Add an id property to our data object with the value of the name property from firebase's response
        data.id = obj.name;

        //Push the data object onto the array
        firebaseApp.shipsArray.push(data);

        //Execute the display function to reload the html from the array
        firebaseApp.display();
    };
    request.onerror = function () {

    };

    request.send(JSON.stringify(data));
};

//Make a HTTP Request to Firebase to grab all the ships that are already in the database and display in a div
firebaseApp.loadFromFirebase = function () {
    var request = new XMLHttpRequest();

    request.open('GET', 'https://sweltering-torch-7921.firebaseio.com/.json', false);
    request.onload = function () {        
        var data = {};

        if (this.status >= 200 && this.status < 400) {
            data = JSON.parse(this.response);
            for (var name in data) {
                firebaseApp.shipsArray.push(data[name]);
            }
        }
    };

    request.onerror = function () {

    }

    request.send();
};

firebaseApp.display = function () {
    var html = '';
    html += '<table>';
    html += '<tr>';
    html += '<th>Affiliation</th><th>Image</th><th>Impounded</th><th>Name</th>';
    html += '</tr>';
    for (var i = 0; i < firebaseApp.shipsArray.length; i++) {
        html += '<tr>';
        html += '<td>' + firebaseApp.shipsArray[i].affiliation + '</td>';
        html += '<td><img src="' + firebaseApp.shipsArray[i].image + '" width="300" height="200" /></td>';
        html += firebaseApp.shipsArray[i].isImpounded ? '<td>Yes</td>' : '<td>No</td>';
        html += '<td>' + firebaseApp.shipsArray[i].name + '</td>';
        html += '</tr>';
    }
    html += '</table>';

    document.getElementById('output').innerHTML = html;
};

//As soon as the script file loads, execute the loadFromFirebase Function to obtain all the previous data and load into the array
firebaseApp.loadFromFirebase();
//After loading up the array, display all the items in the array on the index page
firebaseApp.display();